package com.zline.foodraise.ui.activity;

import android.app.ActivityManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.CommentListAdapter;
import com.zline.foodraise.adapter.PicZoomViewPageAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.CommentBean;
import com.zline.foodraise.entity.JsResourceBean;
import com.zline.foodraise.entity.PictureBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.PhotoViewListener;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.listener.RecyclerOnScrollListener;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.DrawableDividerItemDecoration;
import com.zline.foodraise.view.MyLinearLayoutManager;
import com.zline.foodraise.view.ViewPagerFixed;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by heshantao on 15/8/1.
 * 评论列表
 */
@EActivity(R.layout.activity_comment_list)
public class CommentListActivity extends ZlineActivity implements RecyclerItemClicked, PhotoViewListener {
    private static final String LOG_TAG = CommentListActivity.class.getSimpleName();
    @StringRes(R.string.comment_list)
    String comment_title;
    @StringRes(R.string.topic_list)
    String topic_title;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    @ViewById(R.id.comment_btn)
    Button addComment_btn;
    @ViewById(R.id.comment_list_srl)
    SwipeRefreshLayout swipeRefreshLayout;
    @ViewById(R.id.comment_list_recyclerView)
    RecyclerView recyclerView;
    SparseArray<CommentBean> sparseArray;
    SparseArray<CommentBean> hotCommentArray;
    @Bean
    CommentListAdapter adapter;
    //用于标示是筹评价列表、商品评价列表 2-筹,3-商品
    int resourceType;
    //类型ID
    long resourceId;
    //店老板ID
    long shopkeeperUserId;
    @Extra
    JsResourceBean jsResourceBean;
    @Bean
    HttpUtil httpUtil;
    @Bean
    HttpOperator httpOperator;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    //当前页
    int currt_page = 1;
    //共多少页
    int pageCount;
    int position;
    @Bean
    HttpDataParsing httpDataParsing;
    MyLinearLayoutManager layoutManager;
    //用于添加评论。回复评论，返回刷新数据
    boolean fresh = false;
    @ViewById(R.id.comment_list_fl)
    FrameLayout fl;
    @ViewById(R.id.pics_vp)
    ViewPagerFixed pics_vp;
    @ViewById(R.id.comment_btn)
    Button comment_btn;
    @Bean
    PicZoomViewPageAdapter picZoomViewPageAdapter;
    @Pref
    AppPref_ appPref;
    long userId;
    //是否放大图片了
    boolean zoomPic;
    //评论的点赞数
    int comment_support_num;
    //用来标示普通评论列表，热门评论列表
    int flag;
    @ViewById(R.id.exception_fl)
    FrameLayout exception_fl;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @ViewById(R.id.ex_no_data_rl)
    RelativeLayout no_data_rl;
    @Bean
    NetworkUtil networkUtil;
    //是否加载失败
    boolean loadFail = false;
    //第一次加载数据
    boolean firstLoad = true;
    //加载更多
    boolean loadMore = false;

    @AfterViews
    void doSomeAfterViews() {
        initData();
        initView();
        requestData();
    }

    void initData() {
        if (jsResourceBean == null) return;
        resourceType = jsResourceBean.getType();
        resourceId = jsResourceBean.getResourceId();
        shopkeeperUserId = jsResourceBean.getShopkeeperUserId();
        userId = appPref.userId().get();
        sparseArray = new SparseArray<CommentBean>();
        hotCommentArray = new SparseArray<CommentBean>();
    }

    void initView() {
        if (resourceType == 2) {
            title_tv.setText(topic_title);
            addComment_btn.setText(R.string.release_topic);
        }else{
            title_tv.setText(comment_title);
        }
        //如果是商品评论列表则影藏添加评论的如果(商品的评论入口在订单中)
        if (resourceType == 3) {
            addComment_btn.setVisibility(View.GONE);
        }
        initRecyclerView();
        initSwipRefreshLayout();
    }


    //请求数据
    void requestData() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            requestCommentList();
            requestHostCommentList();
        } else {
            showLoadFailView(true);
            TUtil.showShort(CommentListActivity.this, R.string.no_network);
        }
    }


    //是否加载失败显示重新加载页面
    void showLoadFailView(boolean isException) {
        loadFail = isException;
        if (isException) {
            exception_fl.setVisibility(View.VISIBLE);
            exception_rl.setVisibility(View.VISIBLE);
            addComment_btn.setVisibility(View.GONE);
            if (firstLoad) {
                recyclerView.setVisibility(View.GONE);
            }
        } else {
            exception_fl.setVisibility(View.GONE);
            exception_rl.setVisibility(View.GONE);
            addComment_btn.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }

    //是否显示暂无数据
    void showNoDataView(boolean noData) {
        if (noData) {
            exception_fl.setVisibility(View.VISIBLE);
            no_data_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            no_data_rl.setVisibility(View.GONE);
        }
    }


    //初始化RecyclerView
    void initRecyclerView() {
        recyclerView.addItemDecoration(new DrawableDividerItemDecoration(getResources().getDrawable(R.drawable.recycleview_divider), true, true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        layoutManager = new MyLinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        adapter.setAdapterData(sparseArray);
        adapter.setResourceType(resourceType);
        adapter.setHeaderData(hotCommentArray);
        adapter.setRecycleItemClickListener(this);
        adapter.setRecycleFlag(Constant.COMMENT_FLAG);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                if (currt_page < pageCount) {
                    if (networkUtil.isNetworkAvailable()) {
                        currt_page++;
                        loadMore = true;
                        showRecyclerFoot(true);
                        requestCommentList();
                    } else {
                        TUtil.showShort(CommentListActivity.this, R.string.no_network);
                    }
                }

            }
        });
    }


    //初始化SwipRefreshLayout
    void initSwipRefreshLayout() {
        //设置加载颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (networkUtil.isNetworkAvailable()) {
                    currt_page = 1;
                    requestHostCommentList();
                    requestCommentList();
                } else {
                    stopRefresh();
                    TUtil.showShort(CommentListActivity.this, R.string.no_network);
                }

            }
        });
    }


    //请求热门评论列表
    void requestHostCommentList() {
        httpOperator.requestHostCommentList(httpUtil, resourceType, resourceId, requestHostCommentHandler);
    }

    //获取热门评论列表回调
    AsyncHttpResponseHandler requestHostCommentHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestHostCommentHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        hotCommentArray = httpDataParsing.getCommentList(response);
                        adapter.setHeaderData(hotCommentArray);
                        adapter.notifyItemChanged(0);
                    } else {
                        httpErro.showCommonErroResult(resultCode);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };


    //请求评论列表
    void requestCommentList() {
        httpOperator.requestCommentList(httpUtil, resourceType, resourceId,
                Constant.PAGE_ROWS_NUMBER, currt_page, requestCommentHandler);
    }


    //获取评论列表回调
    AsyncHttpResponseHandler requestCommentHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestCommentHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        sparseArray = httpDataParsing.getCommentList(response);
                        getPageCount(response);
                        if (fresh || swipeRefreshLayout.isRefreshing()) {
                            refreshData(sparseArray);
                        } else {
                            loadMoreData(sparseArray);
                        }

                    } else {
                        loadFailInfo();
                        if (firstLoad) {
                            showLoadFailView(true);
                        } else {
                            httpErro.showCommonErroResult(resultCode);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    firstLoad = false;
                    fresh = false;
                    dissLoadingDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            fresh = false;
            loadFailInfo();
            dissLoadingDialog();
            if (firstLoad) {
                showLoadFailView(true);
            }
        }
    };


    //停止刷新
    void stopRefresh() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    //刷新数据
    void refreshData(SparseArray<CommentBean> array) {
        if (loadFail) {
            showLoadFailView(false);
        }
        adapter.setAdapterData(array);
        adapter.notifyItemRangeChanged(1, array.size());
        stopRefresh();
        isNoDataException();
    }


    //加载更多数据
    void loadMoreData(SparseArray<CommentBean> array) {
        loadMore = false;
        if (currt_page == pageCount) {
            showRecyclerFoot(false);
        }
        if (loadFail) {
            showLoadFailView(false);
        }
        adapter.addAll(array);
        if (currt_page == 1) {
            isNoDataException();
        }
    }

    //是否显示暂时没有数据
    void isNoDataException() {
        int size = adapter.getArrys().size();
        if (size == 0) {
            showNoDataView(true);
            recyclerView.setVisibility(View.GONE);
        } else {
            showNoDataView(false);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }

    //是否显示正在加载
    void showRecyclerFoot(boolean bol) {
        if (adapter != null) {
            adapter.setFootEnable(bol);
            adapter.notifyItemChanged(adapter.getArrys().size() + 1);
        }
    }

    //加载失败时候情况处理
    void loadFailInfo() {
        stopRefresh();
        if (loadMore) {
            currt_page--;
            loadMore = false;
        }
        if (adapter.getFootEnable()) {
            showRecyclerFoot(false);
        }
        firstLoad = false;
    }

    //分页查找共多少页
    @Background
    void getPageCount(JSONObject json) {
        try {
            JSONObject jsonObject = json.getJSONObject(Constant.COMMENT_BEAN_PAGE);
            pageCount = jsonObject.getInt(Constant.PAGE_COUNT);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //请求为评论点赞
    void requestAddCommentSupport(long commentId) {
        if (networkUtil.isNetworkAvailable()) {
            httpOperator.requestAddCommentSupport(httpUtil, commentId, requestAddOrCancelCommentSupportHandler);
        } else {
            TUtil.showShort(CommentListActivity.this, R.string.no_network);
        }
    }


    //取消点赞对话框
    void openCancelCommentSupportDialog(final long commentId) {
        new MaterialDialog.Builder(this)
                .title(R.string.warm_prompt)
                .titleGravity(GravityEnum.CENTER)
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        requestCancelCommentSupport(commentId);
                    }

                    @Override
                    public void onNegative(MaterialDialog dialog) {
                    }
                })
                .content(R.string.cancel_comment_support_dialog_content)
                .positiveText(R.string.ok)
                .negativeText(R.string.cancel)
                .show();
    }

    //请求为评论取消点赞
    void requestCancelCommentSupport(long commentId) {
        if (networkUtil.isNetworkAvailable()) {
            httpOperator.requestCancelCommentSupport(httpUtil, commentId, requestAddOrCancelCommentSupportHandler);
        } else {
            TUtil.showShort(CommentListActivity.this, R.string.no_network);
        }

    }


    //获取为改变评论点赞状态的回调
    AsyncHttpResponseHandler requestAddOrCancelCommentSupportHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestAddOrCancelCommentSupportHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        comment_support_num = response.getInt(Constant.COMMENT_PRAISE_COUNT);
                        refreshCommentSupportStatus(comment_support_num);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };


    //刷新评论点赞状态
    void refreshCommentSupportStatus(int comment_support_num) {
        CommentBean commentBean = null;

        if (flag == Constant.COMMENT_FLAG) {
            commentBean = adapter.getArrys().get(position - 1);
        } else if (flag == Constant.HOT_COMMENT_FLAG) {
            commentBean = hotCommentArray.get(position);
        }
        if (commentBean == null) return;
        commentBean.setIsPraise(commentBean.getIsPraise() == 1 ? 0 : 1);
        commentBean.setCommentPraiseCount(comment_support_num);

        if (flag == Constant.COMMENT_FLAG) {
            adapter.getArrys().put(position - 1, commentBean);
            adapter.notifyItemChanged(position);
        } else {
            hotCommentArray.put(position, commentBean);
            adapter.notifyItemChanged(0);
        }
    }


    @Click({R.id.app_common_header_left_icon_iv, R.id.comment_btn,
            R.id.reload_tv})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.comment_btn://商品评论入口不在这边
                if (appPref.userId().get() > 0) {
                    ReleaseCommentActvity_.intent(this).resourceType(resourceType).
                            resourceId(resourceId).flag(Constant.ADD_COMMENT_FLAG)
                            .startForResult(Constant.COMMENT_LIST_REQUEST_CODE);
                } else {
                    LoginActivity_.intent(this).startForResult(Constant.COMMENT_LIST_REQUEST_CODE);
                }
                break;
            case R.id.reload_tv:
                if (networkUtil.isNetworkAvailable()) {
                    requestHostCommentList();
                }
                requestData();
                break;
            default:
                break;
        }

    }


    @OnActivityResult(Constant.COMMENT_LIST_REQUEST_CODE)
    void onActivityResult(int resultCode) {
        switch (resultCode) {
            case Constant.COMMENT_RESULT_CODE:
                currt_page = 1;
                fresh = true;
                requestData();
                break;
            default:
                break;
        }
    }


    @Override
    public void onBackPressed() {
        if (zoomPic) {
            onViewTap();
        } else {
            goback();
        }
    }


    //点击放大图片
    void showZoomPics(int flag, int position, int parentPosition) {
        CommentBean commentBean = null;
        if (flag == Constant.COMMENT_LIST_PICS_FLAG) {
            commentBean = adapter.getArrys().get(parentPosition - 1);
        } else {
            commentBean = hotCommentArray.get(parentPosition);
        }
        if (commentBean == null) return;
        zoomPic = true;
        List<PictureBean> list = commentBean.getPictureBeanList();
        picZoomViewPageAdapter.setPicList(list);
        picZoomViewPageAdapter.setPhotoViewListener(this);
        pics_vp.setAdapter(picZoomViewPageAdapter);
        pics_vp.setCurrentItem(position);
        fl.setVisibility(View.VISIBLE);
        comment_btn.setVisibility(View.GONE);
    }

    @Override
    public void onRecyclerItemClicked(int position) {

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {
        CommentBean commentBean = null;
        //点击评论列表的一个item
        if (flag == Constant.HOT_COMMENT_LIST_ITEM_FLAG || flag == Constant.COMMENT_LIST_ITEM_FLAG) {
            //商品只有店老板才能回复
            if (resourceType == 3 && userId != shopkeeperUserId) return;

            if (flag == Constant.COMMENT_LIST_ITEM_FLAG) {
                commentBean = adapter.getArrys().get(position - 1);
            } else if (flag == Constant.HOT_COMMENT_LIST_ITEM_FLAG) {
                commentBean = hotCommentArray.get(position);
            }
            if (commentBean == null) return;
            //需要先登录
            if (appPref.userId().get() > 0) {
                ReleaseCommentActvity_.intent(this).resourceType(resourceType).
                        resourceId(resourceId).flag(Constant.REPLY_COMMENT_FLAG)
                        .commentBean(commentBean).startForResult(Constant.COMMENT_LIST_REQUEST_CODE);
            } else {
                LoginActivity_.intent(this).startForResult(Constant.COMMENT_LIST_REQUEST_CODE);
            }

        } else {//点赞、取消赞
            this.position = position;
            this.flag = flag;
            if (flag == Constant.COMMENT_FLAG) {
                commentBean = adapter.getArrys().get(position - 1);
            } else if (flag == Constant.HOT_COMMENT_FLAG) {
                commentBean = hotCommentArray.get(position);
            }
            if (commentBean == null) return;
            int isSupport = commentBean.getIsPraise();
            if (isSupport == 1) {
                openCancelCommentSupportDialog(commentBean.getCommentId());
            } else {
                requestAddCommentSupport(commentBean.getCommentId());
            }
        }
    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {
        if (flag == Constant.COMMENT_LIST_PICS_FLAG || flag == Constant.HOT_COMMENT_LIST_PICS_FLAG) {
            showZoomPics(flag, position, parent);
        }
    }

    @Override
    public void onRecyclerClickedDelete(int position) {

    }

    @Override
    public void onViewTap() {
        zoomPic = false;
        fl.setVisibility(View.GONE);
        if (resourceType == 3) {
            comment_btn.setVisibility(View.GONE);
        } else {
            comment_btn.setVisibility(View.VISIBLE);
        }
    }
}
